package com.negative.activities;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.negative.data.PaymentFormData;
import com.negative.data.PurchaseData;
import com.negative.logic.DialogManager;
import com.negative.logic.MenuListener;
import com.negative.logic.TicketListAdapter;
import com.negative.utils.IOHelper;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

public class PaymentFormActivity extends Activity {

	PaymentFormData data;
	EditText emailET, firstNameET, lastNameET, phoneNumberET, idET,
			cardNumberET, cardHolderIDET, cardHolderNameET, cvvET;
	Spinner areaCodeSpinner, monthSpinner, yearSpinner;
	ListView ticketList;
	TextView eventName, eventLocation, eventStartDate, disclaimer, emailError,
			firstNameError, lastNameError, phoneNumberError, idError,
			cardNumberError, cardHolderIDError, cardHolderNameError, cvvError,
			cardExpirationError, disclaimerError;
	ImageView menuButton;
	MenuListener menuListener;
	TicketListAdapter ticketListAdapter;
	CheckBox checkBox;
	Button order;
	LinearLayout creditCardContainer;
	Context context;
	Activity activity;

	@SuppressLint("SetJavaScriptEnabled")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.payment_form_layout);

		initialize();

		final String html = getIntent().getStringExtra("response");
		new GetHtml().execute(new String[] { html });

	}

	private class GetHtml extends AsyncTask<String, Void, Document> {

		ProgressDialog mProgressDialog;

		@Override
		protected void onPostExecute(Document result) {
			super.onPostExecute(result);
			data = new PaymentFormData(result);
			eventName.setText(getString(R.string.payment_info_event_name)
					+ data.getOrderDetailes().getEventName());
			eventLocation
					.setText(getString(R.string.payment_form_event_location)
							+ data.getOrderDetailes().getLocation());
			eventStartDate
					.setText(getString(R.string.payment_form_event_start_time)
							+ data.getOrderDetailes().getStartTime());

			ticketListAdapter = new TicketListAdapter(context, data
					.getTicketDetails().getTicketTypesData(), data
					.getTicketDetails().getTotalPrice());
			ticketList.setAdapter(ticketListAdapter);
			setListViewHeightBasedOnChildren(ticketList);
			if (!data.getTicketDetails().getTotalPrice().matches(".*[1-9].*")) {
				hideCreditCartFeilds();
			}
			mProgressDialog.dismiss();
		}

		@Override
		protected Document doInBackground(String... params) {
			// TODO Auto-generated method stub
			// android.os.Debug.waitForDebugger();
			try {
				return Jsoup.connect(params[0]).get();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			mProgressDialog = new ProgressDialog(PaymentFormActivity.this);
			mProgressDialog.setTitle(getString(R.string.negative_plus));
			mProgressDialog.setMessage(getString(R.string.loading));
			mProgressDialog.setIcon(R.drawable.negative_plus_icon);
			mProgressDialog.setCanceledOnTouchOutside(false);
			mProgressDialog.show();
		}

	}

	private void initialize() {
		activity = this;
		emailET = (EditText) findViewById(R.id.payment_form_email);
		firstNameET = (EditText) findViewById(R.id.payment_form_first_name);
		lastNameET = (EditText) findViewById(R.id.payment_form_last_name);
		idET = (EditText) findViewById(R.id.payment_form_id_number);
		phoneNumberET = (EditText) findViewById(R.id.payment_form_phone_number);
		cardNumberET = (EditText) findViewById(R.id.payment_form_card_number);
		cardHolderIDET = (EditText) findViewById(R.id.payment_form_card_holder_id);
		cardHolderNameET = (EditText) findViewById(R.id.payment_form_card_holder_name);
		cvvET = (EditText) findViewById(R.id.cvv);
		areaCodeSpinner = (Spinner) findViewById(R.id.area_code_spinner);
		monthSpinner = (Spinner) findViewById(R.id.month_spinner);
		yearSpinner = (Spinner) findViewById(R.id.year_spinner);
		menuButton = (ImageView) findViewById(R.id.menu_icon);
		eventName = (TextView) findViewById(R.id.payment_form_event_name);
		eventLocation = (TextView) findViewById(R.id.payment_form_event_location);
		eventStartDate = (TextView) findViewById(R.id.payment_form_event_start_date);
		emailError = (TextView) findViewById(R.id.payment_form_email_error_label);
		firstNameError = (TextView) findViewById(R.id.payment_form_first_name_error_label);
		lastNameError = (TextView) findViewById(R.id.payment_form_last_name_error_label);
		phoneNumberError = (TextView) findViewById(R.id.payment_form_phone_error_label);
		idError = (TextView) findViewById(R.id.payment_form_id_error_label);
		cardNumberError = (TextView) findViewById(R.id.payment_form_card_number_error_label);
		cardHolderIDError = (TextView) findViewById(R.id.payment_form_card_holder_id_error_label);
		cardHolderNameError = (TextView) findViewById(R.id.payment_form_card_holder_name_error_label);
		cvvError = (TextView) findViewById(R.id.payment_form_cvv_error_label);
		cardExpirationError = (TextView) findViewById(R.id.payment_form_card_expiration_error_label);
		disclaimerError = (TextView) findViewById(R.id.payment_form_disclaimer_error_label);
		ticketList = (ListView) findViewById(R.id.payment_form_ticket_list);
		ticketList.setScrollContainer(false);
		checkBox = (CheckBox) findViewById(R.id.disclaimer_checkbox);
		disclaimer = (TextView) findViewById(R.id.disclaimer);
		disclaimer.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent browserIntent = new Intent(
						Intent.ACTION_VIEW,
						Uri.parse("https://www.tixwise.co.il/he/terms?new_window=1"));
				startActivity(browserIntent);
			}
		});
		order = (Button) findViewById(R.id.payment_form_purchase_button);
		creditCardContainer = (LinearLayout) findViewById(R.id.credit_card_container);
		context = this;

		menuListener = new MenuListener(this);
		menuButton.setOnClickListener(menuListener);
		order.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String email = emailET.getText().toString();
				if (email == null || email.isEmpty()) {
					Thread t = new Thread() {
						public void run() {
							DialogManager.showOKDialog(activity, true,
									getString(R.string.mendatory_feild),
									getString(R.string.missing_email));
						}
					};
					t.start();
					return;
				} else {
					data.getUserDetailes().getEmail().setValue(email);
				}
				String firstName = firstNameET.getText().toString();
				if (firstName == null || firstName.isEmpty()) {
					Thread t = new Thread() {
						public void run() {
							DialogManager.showOKDialog(activity, true,
									getString(R.string.mendatory_feild),
									getString(R.string.missing_first_name));
						}
					};
					t.start();
					return;
				} else {
					data.getUserDetailes().getFirstName().setValue(firstName);
				}
				String lastName = lastNameET.getText().toString();
				if (lastName == null || lastName.isEmpty()) {
					Thread t = new Thread() {
						public void run() {
							DialogManager.showOKDialog(activity, true,
									getString(R.string.mendatory_feild),
									getString(R.string.missing_last_name));
						}
					};
					t.start();
					return;
				} else {
					data.getUserDetailes().getLastName().setValue(lastName);
				}
				String id = idET.getText().toString();
				if (id == null || id.isEmpty()) {
					Thread t = new Thread() {
						public void run() {
							DialogManager.showOKDialog(activity, true,
									getString(R.string.mendatory_feild),
									getString(R.string.missing_id));
						}
					};
					t.start();
					return;
				} else {
					data.getUserDetailes().getId().setValue(id);
				}
				String areaCode = (String) areaCodeSpinner.getSelectedItem();
				if (areaCode == null || areaCode.isEmpty()) {
					Thread t = new Thread() {
						public void run() {
							DialogManager.showOKDialog(activity, true,
									getString(R.string.mendatory_feild),
									getString(R.string.missing_area_code));
						}
					};
					t.start();
					return;
				} else {
					data.getUserDetailes().getPhoneNumberArea()
							.setValue(areaCode);
				}
				String phoneNumber = phoneNumberET.getText().toString();
				if (phoneNumber == null || phoneNumber.isEmpty()) {
					Thread t = new Thread() {
						public void run() {
							DialogManager.showOKDialog(activity, true,
									getString(R.string.mendatory_feild),
									getString(R.string.missing_phone_number));
						}
					};
					t.start();
					return;
				} else {
					data.getUserDetailes().getPhoneNumberNumber()
							.setValue(phoneNumber);
				}
				String cardNumber, cardHolderID, cardHolderName, cvv, month, year;
				if (data.getTicketDetails().getTotalPrice()
						.matches(".*[1-9].*")) {
					cardNumber = cardNumberET.getText().toString();
					if (cardNumber == null || cardNumber.isEmpty()) {
						Thread t = new Thread() {
							public void run() {
								DialogManager
										.showOKDialog(
												activity,
												true,
												getString(R.string.mendatory_feild),
												getString(R.string.missing_card_number));
							}
						};
						t.start();
						return;
					} else {
						data.getPaymentDetails().getCreditNumber()
								.setValue(cardNumber);
					}
					cardHolderID = cardHolderIDET.getText().toString();
					if (cardHolderID == null || cardHolderID.isEmpty()) {
						Thread t = new Thread() {
							public void run() {
								DialogManager
										.showOKDialog(
												activity,
												true,
												getString(R.string.mendatory_feild),
												getString(R.string.missing_card_holder_id));
							}
						};
						t.start();
						return;
					} else {
						data.getPaymentDetails().getOwenrId()
								.setValue(cardHolderID);
					}
					cardHolderName = cardHolderNameET.getText().toString();
					if (cardHolderName == null || cardHolderName.isEmpty()) {
						Thread t = new Thread() {
							public void run() {
								DialogManager
										.showOKDialog(
												activity,
												true,
												getString(R.string.mendatory_feild),
												getString(R.string.missing_card_holder_name));
							}
						};
						t.start();
						return;
					} else {
						data.getPaymentDetails().getOwnerName()
								.setValue(cardHolderName);
					}
					cvv = cvvET.getText().toString();
					if (cvv == null || cvv.isEmpty()) {
						Thread t = new Thread() {
							public void run() {
								DialogManager.showOKDialog(activity, true,
										getString(R.string.mendatory_feild),
										getString(R.string.missing_cvv));
							}
						};
						t.start();
						return;
					} else {
						data.getPaymentDetails().getCvv().setValue(cvv);
					}
					month = (String) monthSpinner.getSelectedItem();
					if (month == null || month.isEmpty()) {
						Thread t = new Thread() {
							public void run() {
								DialogManager
										.showOKDialog(
												activity,
												true,
												getString(R.string.mendatory_feild),
												getString(R.string.missing_card_expiration));
							}
						};
						t.start();
						return;
					} else {
						data.getPaymentDetails().getExpirationMonth()
								.setValue(month);
					}
					year = (String) yearSpinner.getSelectedItem();
					if (year == null || year.isEmpty()) {
						Thread t = new Thread() {
							public void run() {
								DialogManager
										.showOKDialog(
												activity,
												true,
												getString(R.string.mendatory_feild),
												getString(R.string.missing_card_expiration));
							}
						};
						t.start();
						return;
					} else {
						data.getPaymentDetails().getExpirationYear()
								.setValue(year);
					}
				}
				if (!checkBox.isChecked()) {
					Thread t = new Thread() {
						public void run() {
							DialogManager.showOKDialog(activity, true,
									getString(R.string.mendatory_feild),
									getString(R.string.missing_disclaimer));
						}
					};
					t.start();
				} else {
					 data.sendToServer(PaymentFormActivity.this); //only if disclaimer was read
				}
			}
		});
	}

	private void hideCreditCartFeilds() {
		creditCardContainer.getLayoutParams().height = 0;
	}

	public static void setListViewHeightBasedOnChildren(ListView listView) {
		ListAdapter listAdapter = listView.getAdapter();
		if (listAdapter == null)
			return;

		int desiredWidth = MeasureSpec.makeMeasureSpec(listView.getWidth(),
				MeasureSpec.UNSPECIFIED);
		int totalHeight = 0;
		View view = null;
		for (int i = 0; i < listAdapter.getCount(); i++) {
			view = listAdapter.getView(i, view, listView);
			if (i == 0)
				view.setLayoutParams(new ViewGroup.LayoutParams(desiredWidth,
						LayoutParams.WRAP_CONTENT));

			view.measure(desiredWidth, MeasureSpec.UNSPECIFIED);
			totalHeight += view.getMeasuredHeight();
		}
		ViewGroup.LayoutParams params = listView.getLayoutParams();
		params.height = totalHeight
				+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));
		listView.setLayoutParams(params);
		listView.requestLayout();
	}

	public void createEtickect (PurchaseData data){
		ArrayList<PurchaseData> purchases = new ArrayList<PurchaseData>();
		try{
			purchases = IOHelper.ReadPurchases(context);
		}catch (Exception e){
		}
			purchases.add(data);
			try{
			IOHelper.WritePurchases(context, purchases);
			Intent i = new Intent(context, PurchaseListActivity.class);
			i.putExtra("toHome", true);
			startActivity(i);
			finish();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void returnWithErrors(HashMap<String, String> errors) {

		String label = getString(R.string.email_label_tixwise); 
		if (errors.containsKey(label)) {
			emailError.setText(errors.get(label));
			LayoutParams params = emailError.getLayoutParams();
			params.height = LayoutParams.WRAP_CONTENT;
			emailError.setLayoutParams(params);
		}
		label = getString(R.string.first_name_tixwise);
		if (errors.containsKey(label)) {
			firstNameError.setText(errors.get(label));
			LayoutParams params = firstNameError.getLayoutParams();
			params.height = LayoutParams.WRAP_CONTENT;
			firstNameError.setLayoutParams(params);
		}
		label = getString(R.string.last_name_tixwise);
		if (errors.containsKey(label)) {
			lastNameError.setText(errors.get(label));
			LayoutParams params = lastNameError.getLayoutParams();
			params.height = LayoutParams.WRAP_CONTENT;
			lastNameError.setLayoutParams(params);
		}
		label = getString(R.string.id_number_tixwise);
		if (errors.containsKey(label)) {
			idError.setText(errors.get(label));
			LayoutParams params = idError.getLayoutParams();
			params.height = LayoutParams.WRAP_CONTENT;
			idError.setLayoutParams(params);
		}
		label = getString(R.string.phone_number_tixwise);
		if (errors.containsKey(label)) {
			phoneNumberError.setText(errors.get(label));
			LayoutParams params = phoneNumberError.getLayoutParams();
			params.height = LayoutParams.WRAP_CONTENT;
			phoneNumberError.setLayoutParams(params);
		}
		label = getString(R.string.credit_number_tixwise);
		if (errors.containsKey(label)) {
			cardNumberError.setText(errors.get(label));
			LayoutParams params = cardNumberError.getLayoutParams();
			params.height = LayoutParams.WRAP_CONTENT;
			cardNumberError.setLayoutParams(params);
		}
		label = getString(R.string.card_holder_id_tixwise);
		if (errors.containsKey(label)) {
			cardHolderIDError.setText(errors.get(label));
			LayoutParams params = cardHolderIDError.getLayoutParams();
			params.height = LayoutParams.WRAP_CONTENT;
			cardHolderIDError.setLayoutParams(params);
		}
		label = getString(R.string.card_holder_name_tixwise);
		if (errors.containsKey(label)) {
			cardHolderNameError.setText(errors.get(label));
			LayoutParams params = cardHolderNameError.getLayoutParams();
			params.height = LayoutParams.WRAP_CONTENT;
			cardHolderNameError.setLayoutParams(params);
		}
		label = getString(R.string.card_expiration_tixwise);
		if (errors.containsKey(label)) {
			cardExpirationError.setText(errors.get(label));
			LayoutParams params = cardExpirationError.getLayoutParams();
			params.height = LayoutParams.WRAP_CONTENT;
			cardExpirationError.setLayoutParams(params);
		}
		label = getString(R.string.cvv_tixwise);
		if (errors.containsKey(label)) {
			cvvError.setText(errors.get(label));
			LayoutParams params = cvvError.getLayoutParams();
			params.height = LayoutParams.WRAP_CONTENT;
			cvvError.setLayoutParams(params);
		}
		
	}
}
